﻿Imports System.Threading

Public Class ListaClientes
    Private _cliStoreProc As String
    Private _countStoreProc As String
    Private _delStoreProc As String
    Private _fromPedido As Boolean = False
    Private Shared _modifyForm As String = ""
    Private CliCount As UInt16

    Private indice As UInt16 = 0
    Private perPage As UInt16 = 10
    Private Campo As String
    Private criterio As String = ""

    Private totalPages As UInt16
    Private codCliente As UInt16 = 0
    Private cliRow As UInt16
    Private binding1 As New BindingSource

    ReadOnly Property idCliente() As Integer
        Get
            Return codCliente
        End Get
    End Property

    WriteOnly Property cliStoreProc() As String
        Set(ByVal value As String)
            _cliStoreProc = value
        End Set
    End Property

    WriteOnly Property countStoreProc() As String
        Set(ByVal value As String)
            _countStoreProc = value
        End Set
    End Property

    WriteOnly Property delStoreProc() As String
        Set(ByVal value As String)
            _delStoreProc = value
        End Set
    End Property

    WriteOnly Property modifyForm() As String
        Set(ByVal value As String)
            _modifyForm = value
        End Set
    End Property

    WriteOnly Property fromPedido() As Boolean
        Set(ByVal value As Boolean)
            _fromPedido = value
        End Set
    End Property

    Private Sub ListaClientes_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Select Case Me.Text
            Case "Listado Clientes"
                Main.ClientesMenu.Enabled = True
            Case "Listado Representantes"
                Main.VendorsMenu.Enabled = True
            Case "Listado Fabricantes"
                Main.FrabricantesMenu.Enabled = True
        End Select
    End Sub

    Private Sub frmMdiChild_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Label3.Text = ListaClientes._modifyForm.ToUpper
        refrescarDataGrid()
        DataGridView1.DataSource = binding1
        For i As Integer = 0 To DataGridView1.ColumnCount - 1
            'Console.WriteLine("Nombre: {0} - Tipo: {1}", DataGridView1.Columns(i).Name, DataGridView1.Columns(i).ValueType)
            If DataGridView1.Columns(i).ValueType.ToString = "System.String" Then FindByCombo.Items.Add(DataGridView1.Columns(i).Name)
        Next
        FindByCombo.SelectedIndex = 0
    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
    Handles TextBox1.KeyPress
        perPage = Convert.ToInt16(TextBox1.Text)
        If e.KeyChar = vbCr Then
            indice = 1
            refrescarDataGrid()
            refrescarBotones()
        Else
            e.Handled = TextStiles.NumbersOnly(e.KeyChar, sender)
        End If
    End Sub

    Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles RadioButton1.CheckedChanged
        If Not inicializando Then
            If CliCount > 0 Then indice = 1
            perPage = Convert.ToInt16(TextBox1.Text)
            TextBox1.Enabled = True
            GroupBox1.Enabled = True
            refrescarDataGrid()
            refrescarBotones()
        End If
    End Sub

    Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles RadioButton2.CheckedChanged
        If Not inicializando Then
            indice = 0
            TextBox1.Enabled = False
            GroupBox1.Enabled = False
            refrescarDataGrid()
        End If
    End Sub

    Public Sub refrescarDataGrid()
        'nuestroThread = New Thread(nuestroThreadStart)
        'nuestroThread.Start()
        Main.ToolStripStatusLabel1.Text = "Actualizando listado " + _modifyForm
        CliCount = DataAccess.GetClientCount(_countStoreProc, Campo, criterio)
        GroupBox2.Enabled = Convert.ToBoolean(CliCount)
        BtnDel.Enabled = Convert.ToBoolean(CliCount)
        BtnModify.Enabled = Convert.ToBoolean(CliCount)
        totalPages = CliCount \ perPage
        If GroupBox1.Enabled Then
            If CliCount Mod perPage Then totalPages += 1
            LblPagina.Text = indice.ToString + "/" + totalPages.ToString
        Else
            LblPagina.Text = 0
        End If
        Try
            binding1.DataSource = DataAccess.GetListaClientes(_cliStoreProc, indice, perPage, Campo, criterio)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
        'nuestroThread.Abort()
        Main.ToolStripStatusLabel1.Text = ""
    End Sub

    Private Sub refrescarBotones()
        BtnNext.Enabled = Convert.ToBoolean(totalPages - indice)
        BtnLast.Enabled = Convert.ToBoolean(totalPages - indice)
        BtnPrevious.Enabled = Convert.ToBoolean(indice - 1)
        BtnFirst.Enabled = Convert.ToBoolean(indice - 1)
    End Sub

    Private Sub BtnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles BtnNext.Click, BtnFirst.Click, BtnPrevious.Click, BtnLast.Click
        Select Case sender.name
            Case "BtnNext"
                indice += 1
            Case "BtnFirst"
                indice = 1
            Case "BtnPrevious"
                indice -= 1
            Case "BtnLast"
                indice = totalPages
        End Select
        refrescarBotones()
        refrescarDataGrid()
    End Sub

    Private Sub DataGridView1_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
        If e.RowIndex >= 0 Then
            If _fromPedido Then
                Me.Close()
            Else
                modifyCliente()
            End If
        End If
    End Sub

    Private Sub DataGridView1_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEnter
        codCliente = sender.Rows(e.RowIndex).Cells(0).Value
    End Sub

    Private Sub DataGridView1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
        Try
            Dim hti As DataGridView.HitTestInfo = sender.HitTest(e.X, e.Y)  'HitTest to find out Row Index
            If hti.Type = DataGridViewHitTestType.Cell And hti.RowIndex >= 0 Then
                'codCliente = sender.Rows(hti.RowIndex).Cells(0).Value
                cliRow = hti.RowIndex
                If e.Button = Windows.Forms.MouseButtons.Right Then                 'Run on mouse right button click
                    sender.ContextMenuStrip = CnMenu
                    CnMenu.Show(sender, New Point(e.X, e.Y))
                    If Not sender.Rows(hti.RowIndex).Selected Then
                        sender.ClearSelection()                                 'Clear previous selection
                        sender.CurrentCell = sender.Rows(hti.RowIndex).Cells(0) 'Set the current cell
                        sender.Rows(hti.RowIndex).Selected = True               'Do the selection
                    End If
                End If
            End If
        Catch ex As Exception
        End Try
        sender.ContextMenuStrip = Nothing
    End Sub

    Private Sub deleteClient(ByVal name As String)
        Dim msg = "¿Desea eliminar al cliente " + name + "?"
        Dim title = "¡Advertencia!"
        Dim style = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or _
                    MsgBoxStyle.Critical
        If IIf(MsgBox(msg, style, title) = MsgBoxResult.Yes, True, False) Then
            If DataAccess.DeleteRecord(_delStoreProc, codCliente) Then
                Main.ToolStripStatusLabel1.Text = "Cliente " + name + " Eliminado"
                refrescarDataGrid()
            Else
                MessageBox.Show("¡Error!. No se ha eliminado el cliente " + name)
            End If
        End If
    End Sub

    Private Sub modifyCliente()

        Select Case _modifyForm
            Case "Clientes"
                Dim myForm As New Clientes
                With myForm
                    '.Size = New System.Drawing.Size(700, 422)
                    .indic = codCliente
                    .nuevo = False
                    .ShowDialog()
                End With
            Case "Representantes"
                Dim myForm As New Representantes
                With myForm
                    '.Size = New System.Drawing.Size(700, 422)
                    .indic = codCliente
                    .nuevo = False
                    .ShowDialog()
                End With
            Case "Fabricante"
                Dim myForm As New Fabricante
                With myForm
                    '.Size = New System.Drawing.Size(700, 422)
                    .indic = codCliente
                    .nuevo = False
                    .ShowDialog()
                End With
        End Select

    End Sub

    Private Sub ModificarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles ModificarToolStripMenuItem.Click
        modifyCliente()
    End Sub

    Private Sub EliminarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles EliminarToolStripMenuItem.Click, BtnDel.Click
        deleteClient(DataGridView1.Rows(cliRow).Cells(1).Value)
    End Sub

    Private Sub BtnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNuevo.Click
        Select Case _modifyForm
            Case "Clientes"
                Dim myForm As New Clientes
                With myForm
                    .nuevo = True
                    .ShowDialog()
                End With
            Case "Representantes"
                Dim myForm As New Representantes
                With myForm
                    .nuevo = True
                    .ShowDialog()
                End With
            Case "Fabricante"
                Dim myForm As New Fabricante
                With myForm
                    .nuevo = True
                    .ShowDialog()
                End With
        End Select
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Close()
        Me.Dispose()
    End Sub

    Private Sub FindByCombo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindByCombo.SelectedIndexChanged
        Campo = sender.SelectedItem.ToString
    End Sub

    Private Sub FindCombo_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles FindCombo.TextChanged, FindCombo.SelectedIndexChanged
        criterio = sender.text
        refrescarDataGrid()
    End Sub

    Class ThreadWork
        Public Shared Sub DoWork()
            Try

            Catch e As ThreadAbortException
                'Main.ToolStripStatusLabel1.Text = ""
                Thread.ResetAbort()
            End Try
        End Sub 'DoWork
    End Class 'ThreadWork

    Private Sub ImprimirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles ImprimirToolStripMenuItem.Click

    End Sub

    Private Sub BtnModify_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnModify.Click
        modifyCliente()
    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub

End Class